package Year22_Month04.day17;

import java.util.LinkedList;
import java.util.List;

public class 螺旋矩阵 {
    public static List<Integer> spiralOrder(int[][] matrix) {
        LinkedList<Integer> list = new LinkedList<>();
        if(matrix == null || matrix.length == 0){
            return list;
        }

        int left = 0;//定义左边界
        int right = matrix[0].length - 1;//定义右边界

        int top = 0;//定义上边界
        int bottom = matrix.length - 1;//定义下边界

        int count = matrix.length * matrix[0].length;//记录数组种类

        //这里我的遍历思想是左闭右闭
        while(count >= 1){
            //先从左上到右上
            for (int i = left; i <= right && count >= 1; i++) {
                list.add(matrix[top][i]);
                count--;
            }
            top++;

            //再从右上到右下
            for (int i = top; i <= bottom && count >= 1; i++) {
                list.add(matrix[i][right]);
                count--;
            }
            right--;

            //再从右下到左下
            for(int i = right;i >= left && count >= 1;i--){
                list.add(matrix[bottom][i]);
                count--;
            }
            bottom--;

            //再从左下到左上
            for (int i = bottom; i >= top && count >= 1; i--) {
                list.add(matrix[i][left]);
                count--;
            }
            left++;
        }
        return list;
    }

    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(spiralOrder(arr));
    }
}
